
import fs from 'fs'
import path from 'path'
import Parser from './parser'
import checker from './ast/check'

function readFile (file) {
  return fs.readFileSync(file, 'utf8')
}

function readdir (dir) {
  return fs.readdirSync(dir)
}

main()

function main () {
  let
    parser = new Parser(),
    fixture = [],
    totalSize = 0,
    totalTime = 0,
    argv = process.argv.slice(2),
    fmt = false,
    test = false,
    check = false,
    flags = {
      'c':() => {check = true},
      'f':() => {fmt = true},
      't':() => {test = true},
    }

  if (!argv.length)
    argv = ['../modules/any/*.zxx']

  argv.forEach(s => {
    if (s.startsWith('--'))
      return Array.from(s.slice(2)).forEach(f => {
        f = flags[f]
        if (f) f()
      })
    s = path.resolve(s)
    let
      dir = path.dirname(s),
      a = path.basename(s) === '*.zxx'
      && readdir(dir).filter(s =>
        path.extname(s) === '.zxx'
      ).map(s => path.join(dir, s))
      || path.extname(s) === '.zxx'
      && [s]
      || []

    a.forEach(s => {
      if (
        fs.existsSync(s)
      && fs.statSync(s).isFile()
      ) {
        let src = readFile(s)
        if (src) {
          totalSize += src.length
          fixture.push([src, s])
        }
      }
    })
  })

  let mods = []
  totalTime = Date.now()

  fixture.forEach(function ([src, path]) {
    parser.parse(src, !test && path || '')
  })

  totalTime = Date.now() - totalTime

  if (check)
    checker(parser.result)

  if (fmt || test) {
    let good = parser.result.normalize()
    if (test) {
      if (fixture.length > 1)
        console.log('testing for one file only')
      else {
        let well = good.split('\n')

        new Parser().parse(good, '').normalize()
          .split('\n').forEach((s, i) => {
            if (s === well[i]) return
            console.log('Difference line:', i)
            console.log(well[i])
            console.log(s)
            throw Error('oop')
          })

      }
    }
    if (fmt || fixture.length === 1)
      console.log(good)
    walk(parser.result)
  }

  console.log(fixture.length + ' files ' +
    (totalSize / 1024).toFixed(2) + ' KiB ' +
    totalTime.toFixed(2) + ' ms'
  )
}

function walk (x) {
  if (!x.factor) console.log(x.constructor.name)
  if (!x.result) console.log(x.constructor.name)
  x.factor(walk)
  x.result(walk)
  x.items && x.items.forEach(walk)
}

